<template>
	<div class="flex" style="border-left: 1px #eaeaea solid; border-bottom: 1px #eaeaea solid; border-right: 1px #eaeaea solid;">

    <div class="zuobian" style="width: 380px; height: calc(100vh - 105px);  border-right:1px #eaeaea solid; overflow: auto; position: relative;">
      <div style="height: 50%; overflow: auto; border-bottom: 5px rgb(234, 234, 234) solid; padding: 20px;">

        <el-tree  class="filter-tree" @node-click="handleNodeClick" :data="data" :props="defaultProps" node-key="treeId"
                  :default-expanded-keys="zhankaiarray" @node-expand="handleNodeExpand" @node-collapse="handleNodeCollapse" :filter-node-method="filterNode" ref="tree">
        </el-tree>
      </div>
      <div style="position: absolute; left: 0; bottom: 0; background: #fff; width: 100%; height: calc(50% - 10px); overflow: auto;">

        <div>
          <el-table  ref="multipleTable"  :data="tableData"  tooltip-effect="dark"  style="width: 100%"  @selection-change="handleSelectionChange">
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="time" label="采样时间"></el-table-column>
              <el-table-column prop="cyl" label="采样值"></el-table-column>
              <el-table-column prop="stationsNo" label="仪器序列号"></el-table-column>
              <el-table-column prop="beizhu" label="备注"></el-table-column>
            </el-table>
        </div>
      </div>
    </div>

    <div class="youbian" style="padding: 20px; width: calc(100vw - 680px);">
      <div id="main2" style="width: 100%; height: 500px;"></div>
    </div>

    <div v-show="menuVisible" class="custom-menu" :style="{left: menuPosition.x + 'px', top: menuPosition.y + 'px'}" >
      <div class="li" @click="shiyuzhibiaologshow" >时域指标信息</div>
      <!-- <div class="li" @click="shiyuzhibiaolog2 = true" >工艺量均值</div> -->
    </div>

    <el-dialog title="时域指标信息" center :visible.sync="shiyuzhibiaolog" width="900px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
      <el-table :data="data3"  style="width: 100%" >
        <el-table-column align="center" prop="index" label="序号"></el-table-column>
        <el-table-column align="center" prop="name" label="指标名称"></el-table-column>
        <el-table-column align="center" prop="value" label="指标值"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="工艺量均值" center :visible.sync="shiyuzhibiaolog2" width="900px"  :close-on-click-modal="false" :close-on-press-escape="false" :modal-append-to-body="true">
      <el-table :data="data2"  style="width: 100%" >
        <el-table-column align="center" prop="index1" label="工艺量名称"></el-table-column>
        <el-table-column align="center" prop="index2" label="值"></el-table-column>
        <el-table-column align="center" prop="index3" label="采集时间"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>

import testarr from '@/common/testarr'
import * as echarts from 'echarts'
import { gettreecedian } from '@/api/xitong'
import { getanalysis } from '@/api/shujuchakan'
export default {
  name: 'left',
  data () {
    return {
      filterText: '',
      data: [],
      data3: [
        {index: 1, name: '总值', value: 0},
        {index: 1, name: '峭度指标', value: 0},
        {index: 1, name: '脉冲指标', value: 0},
        {index: 1, name: '波形指标', value: 0},
        {index: 1, name: '裕度指标', value: 0},
        {index: 1, name: '歪度指标', value: 0},
        {index: 1, name: '峰值指标', value: 0},
        {index: 1, name: '方根幅值', value: 0},
        {index: 1, name: '最大值', value: 0},
        {index: 1, name: '最小值', value: 0},
        {index: 1, name: '均值', value: 0},
        {index: 1, name: '平均幅值', value: 0}
      ],
      data2: [
        {index1: 1, index2: 2, index3: 3},
        {index1: 1, index2: 2, index3: 3},
        {index1: 1, index2: 2, index3: 3}
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      menuVisible: false,
      shiyuzhibiaolog: false,
      shiyuzhibiaolog2: false,
      menuPosition: { x: 0, y: 0 },

      youjiandangqian: '',
      zhankaiarray: [],

      tableData: [

      ],

      myChart: '',
      youjiandangqian: '',

      zhexiantushuju: []

    }
  },
  created () {
    this.getlist()
  },
  mounted () {

  },
  methods: {
    shiyuzhibiaologshow: function () {
      this.data3 = [
        {index: 1, name: '总值', value: 0},
        {index: 2, name: '峭度指标', value: 0},
        {index: 3, name: '脉冲指标', value: 0},
        {index: 4, name: '波形指标', value: 0},
        {index: 5, name: '裕度指标', value: 0},
        {index: 6, name: '歪度指标', value: 0},
        {index: 7, name: '峰值指标', value: 0},
        {index: 8, name: '方根幅值', value: 0},
        {index: 9, name: '最大值', value: 0},
        {index: 10, name: '最小值', value: 0},
        {index: 11, name: '均值', value: 0},
        {index: 12, name: '平均幅值', value: 0}
      ]
      this.data3[7].value = calculateAverageSquareRootSquared(testarr)
      this.data3[8].value = findMax(testarr)
      this.data3[9].value = Math.min(...testarr)
      this.data3[10].value = average(testarr)
      this.data3[0].value = testarr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
      this.data3[1].value = calculateKurtosis(testarr)
      this.data3[5].value = calculateSkewness(testarr)
      this.data3[4].value = this.data3[8].value / this.data3[7].value
      let youxiaozhi = calculateRMS(testarr)
      this.data3[11].value = averageMagnitude(testarr)

      this.data3[6].value = this.data3[8].value / youxiaozhi
      this.data3[2].value = this.data3[8].value / this.data3[11].value
      this.data3[2].value = this.data3[8].value / this.data3[7].value
      this.data3[3].value = youxiaozhi / this.data3[11].value

      // 峰值指标：最大值/有效值
      // 脉冲指标：最大值/平均幅值
      // 裕度指标：最大值/方根幅值
      // 波形指标：有效值/平均幅值

      // 平均幅值：就是所有绝对值求平均
      function averageMagnitude (arr) {
        // 计算数组中所有值的绝对值
        let absoluteValues = arr.map(Math.abs)
        // 计算绝对值的平均值
        return absoluteValues.reduce((sum, value) => sum + value, 0) / absoluteValues.length
      }

      // 有效值：所有值平方的平均值，最后取平方根
      function calculateRMS (signal) {
        // 计算平方的平均值
        let sumOfSquares = signal.reduce((acc, val) => acc + val * val, 0)
        let averageOfSquares = sumOfSquares / signal.length

        // 计算有效值（RMS）
        let rms = Math.sqrt(averageOfSquares)

        return rms
      }

      // 歪度指标：
      function calculateSkewness (data) {
        // 计算均值  可以用之前算好的均值
        let mean = data.reduce((sum, value) => sum + value, 0) / data.length

        // 计算方差和标准差
        let variance = data.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / data.length
        let stdDeviation = Math.sqrt(variance)

        // 计算三阶中心矩
        let m3 = data.reduce((sum, value) => sum + Math.pow(value - mean, 3), 0) / data.length

        // 计算偏度
        let skewness = m3 / (stdDeviation * stdDeviation * stdDeviation)

        return skewness
      }

      // 峭度指标：
      function calculateKurtosis (data) {
        // 计算平均值    可以用之前算好的均值
        let mean = data.reduce((sum, value) => sum + value, 0) / data.length
        // 计算方差（标准差的平方）
        let variance = data.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / data.length

        // 如果方差为0，峭度未定义，返回NaN
        if (variance === 0) {
          return NaN
        }

        // 计算四阶中心矩
        let fourthMoment = data.reduce((sum, value) => sum + Math.pow(value - mean, 4), 0) / data.length

        // 计算峭度
        let kurtosis = fourthMoment / Math.pow(variance, 2) - 3

        return kurtosis
      }

      // 方根幅值：
      function calculateAverageSquareRootSquared (numbers) {
        // 计算每个数的绝对值的平方根
        let squareRoots = numbers.map(num => Math.sqrt(Math.abs(num)))
        // 计算平方根的总和
        let sumOfSquareRoots = squareRoots.reduce((acc, val) => acc + val, 0)

        // 计算平均值
        let averageSquareRoot = sumOfSquareRoots / numbers.length

        // 计算平均值的平方
        let averageSquareRootSquared = averageSquareRoot * averageSquareRoot // 或者使用 Math.pow(averageSquareRoot, 2)

        return averageSquareRootSquared
      }
      // 最大值
      function findMax (arr) {
        let max = arr[0]
        for (let i = 1; i < arr.length; i++) {
          if (arr[i] > max) {
            max = arr[i]
          }
        }
        return max
      }
      // 平均值
      function average (arr) {
        var sum = 0
        for (var i = 0; i < arr.length; i++) {
          sum += arr[i]
        }
        return sum / arr.length
      }

      this.shiyuzhibiaolog = true
    },
    closeMenu () {
      // 右键取消赋值
      // this.youjiandangqian = ""
      this.menuVisible = false
      console.log(this.menuVisible)
      document.removeEventListener('click', this.closeMenu) // 移除点击事件监听
    },

    // 折线图
    shengchengtu: function () {
      this.option = {
        title: {
          text: '测点图'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: 'test_name',
            type: 'line',
            stack: 'Total',
            data: this.zhexiantushuju
          }
        ]
      }

      if (this.myChart) {
        this.myChart.setOption(this.option)
      } else {
        var chartDom = document.getElementById('main2')
        this.myChart = echarts.init(chartDom)
        this.myChart.setOption(this.option)

        var that = this
        chartDom.addEventListener('contextmenu', function (event) {
          event.preventDefault()

          that.menuPosition.x = event.clientX
          that.menuPosition.y = event.clientY
          that.menuVisible = true

          console.log(that.menuVisible)

          document.addEventListener('click', that.closeMenu)
        })
      }
    },
    // 选中测点 生成折线图
    handleSelectionChange: function (val) {
      // 测试
      this.zhexiantushuju = testarr
      this.shengchengtu()

      // 真
      // let data = []
      // val.forEach((item)=>{
      //   let obj = {
      //     "ip": item.ip,
      //     "tongDao": item.tongDao,
      //     "time": item.time,
      //     "tdLx": item.tdLx,
      //     "treeName": item.treeName
      //   }
      //   data.push(obj)
      // })
      // let arr = []
      // postanalysis(data).then(response => {
      //   response.data.forEach(item=>{
      //     arr = [...arr,...item.points]
      //   })

      //   this.zhexiantushuju = arr

      //   this.shengchengtu()
      // })
    },
    // 当节点展开
    handleNodeExpand (data, node, instance) {
      this.zhankaiarray.push(data.treeId)
    },
    // 当节点折叠
    handleNodeCollapse (data, node, instance) {
      const index = this.zhankaiarray.indexOf(data.treeId)
      if (index > -1) {
        this.zhankaiarray.splice(index, 1)
      }
    },

    // 点击测点获取日志
    handleNodeClick (data) {
      if (data.type == 21 || data.type == 22 || data.type == 23) {
        getanalysis(data.value).then(response => {
          // this.tableData = response.data
          this.tableData = [{time: '2024-5-30', cyl: '7701', stationsNo: '1', beizhu: '测试'}]
        })
      }
    },

    filterNode (value, data) {
      // if (!value) return true;
      // return data.label.indexOf(value) !== -1;
    },
    getlist: function () {
      gettreecedian().then(response => {
        this.data = response.data
      })
    }
  }
}
</script>

<style scoped lang="less">

  .custom-menu {
    position: fixed;
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 5px;
    overflow: hidden;
    z-index: 3000;

  }
  .li{
    cursor: pointer; color: #005AFF; padding:10px 20px; font-size: 12px;
    &:hover{ background: #005AFF !important; color:#fff !important;}
  }

</style>
